package com.youlu.campus.admin.order;

import com.youlu.campus.admin.annotation.RequestActivityAuth;
import com.youlu.campus.admin.auth.entity.SystemUser;
import com.youlu.campus.admin.auth.service.UserService;
import com.youlu.campus.admin.cert.OrderCertService;
import com.youlu.campus.admin.utils.AuthUtils;
import com.youlu.campus.admin.utils.IpUtils;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.base.order.vo.OrderRequest;
import com.youlu.campus.common.base.RestResult;
import com.youlu.campus.common.base.RestResultBuilder;
import com.youlu.campus.entity.OrderCommentInfo;
import com.youlu.campus.entity.OrderInfo;
import com.youlu.campus.entity.VO.req.CreateCaOrderTagVO;
import com.youlu.campus.entity.VO.req.OrderRefundOptVO;
import com.youlu.campus.service.order.OrderInfoTipService;
import com.youlu.campus.service.order.OrderService;
import com.yuelin.infrastructure.quantum.common.QResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 订单管理接口
 * @author: YangJ
 * @date: 2020/12/28 13:53
 */
@Slf4j
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderInfoTipService orderInfoTipService;

    @Autowired
    private OrderCertService orderCertService;


    private final static String [] EXPORT_ORDER_USER = {"zhuhuaiqi","lihui","liangjinqiu","yangyang","liuyun","liukun","beibei"};

    /**
     * 纸质证书订单
     * @return
     */
    @PostMapping("/order/paper-ca/list")
    public RestResult paperCaOrderList(@RequestBody OrderRequest request){
        String userId = AuthUtils.getUserId();
        request.setUserId(userId);
        return RestResultBuilder.builder().success().data(orderService.paperCaOrderList(request)).build();
    }

    /**
     * 订单列表
     * @param request
     * @return
     */
    @PostMapping("/order/page")
    public QResult orderPage(@RequestBody OrderRequest request) {
        request.setOptUserName(AuthUtils.getLoginName());
        return QResult.success(orderService.getUserOrderPage(request));
    }

    /**
     * 纸质证书导出接口
     * @param request
     * @return
     */
    @PostMapping("/order/cert/make/export")
    public QResult order(@RequestBody OrderRequest request) {
        orderCertService.orderCertMakeAndExport(request,AuthUtils.getLoginName(), AuthUtils.getUserId());
        return QResult.success("ok");
    }

    /**
     * 订单收货人地址修改
     * @param request
     * @return
     */
    @PostMapping("/order/address/update")
    public QResult addressUpdate(@RequestBody com.youlu.campus.entity.domain.OrderUpdateRequest request) {
        String userId = AuthUtils.getUserId();
        SystemUser systemUser = userService.get(userId);
        if (Objects.nonNull(systemUser)) {
            request.setOptUser(systemUser.getRealName());
        }else{
            request.setOptUser(userId);
        }
        request.setSourcePlatform("赞我云平台");
        return QResult.success(orderService.addressUpdate(request));
    }

    @GetMapping("/order/find-one")
    public QResult findOne(@RequestParam("id") String id) {

        return QResult.success(orderService.findOne(id));
    }

    @PostMapping("/order/create-tag")
    public RestResult createTag(@RequestBody CreateCaOrderTagVO req) {
        String comId = AuthUtils.getComId();
        List<String> tags = orderService.createTags(req);
        return RestResultBuilder.builder().success().data(tags).build();
    }

    @PostMapping("/order/delete-tag")
    public RestResult deleteTag(@RequestBody CreateCaOrderTagVO req) {
        String comId = AuthUtils.getComId();
        List<String> tags = orderService.deleteTags(req);
        return RestResultBuilder.builder().success().data(tags).build();
    }

    @PostMapping("/order/create-comment")
    public RestResult createComment(@RequestBody OrderCommentInfo req) {
        String comId = AuthUtils.getComId();
//        req.setOptName(AuthUtils.getLoginName());
        boolean res = orderService.createComment(req);
        return RestResultBuilder.builder().success().build();
    }

    @PostMapping("/order/comments")
    public RestResult getComment(@RequestBody OrderCommentInfo req) {
        String comId = AuthUtils.getComId();
        List<OrderCommentInfo> caInfos = orderService.getComments(req);
        return RestResultBuilder.builder().success(caInfos).build();
    }

    @GetMapping("/order/analysis")
    public RestResult orderAnalysis() {
        String comId = AuthUtils.getComId();
        orderService.orderAnalysis();
        return RestResultBuilder.builder().success().build();
    }

    @PostMapping("/order/shipping")
    public RestResult shipping(@RequestBody OrderInfo req) {
        String comId = AuthUtils.getComId();
        boolean res = orderService.shipping(req);
        if (res) {
            return RestResultBuilder.builder().success().build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    /**
     * 订单导出
     *
     * @param
     * @param
     */
    @PostMapping("/order/export")
    @RequestActivityAuth(activityId = "#req.activityId")
    public RestResult orderExport(@RequestBody OrderRequest req, HttpServletRequest request) {
        req.setUserId(AuthUtils.getUserId());
        SystemUser systemUser = userService.get(req.getUserId());
        if (Objects.isNull(systemUser)) {
           throw new BusinessException("没有权限导出订单");
        }
        String loginName = systemUser.getLoginName();
        log.info("【导出订单】loginName:{}",loginName);
//        long count = Arrays.stream(EXPORT_ORDER_USER).filter(exportUser -> exportUser.equals(loginName)).count();
//        if(count==0){
//            throw new BusinessException("对不起，您当前没有权限导出订单数据");
//        }
        req.setOptUserName(systemUser.getLoginName());
        req.setOptUserRealName(systemUser.getRealName());
        String ip = IpUtils.getIpAddr(request);
        req.setIpAddress(ip);
        String result = orderService.export(req, null);
        log.info(":>>> 导出订单结果:{}", result);
        if (StringUtils.isNotBlank(result)) {
            return RestResultBuilder.builder().success(result).build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    /**
     * 供应链批量导出
     * 对应前端
     *
     * @param
     * @param
     */
    @PostMapping("/order-express/export")
    @RequestActivityAuth(activityId = "#req.activityId")
    public RestResult orderExpressExport(@RequestBody OrderRequest req, HttpServletRequest request) {
        req.setUserId(AuthUtils.getUserId());
        SystemUser systemUser = userService.get(req.getUserId());
        if (Objects.isNull(systemUser)) {
            throw new BusinessException("没有权限导出订单");
        }
        String loginName = systemUser.getLoginName();
        log.info("【导出订单】orderExpressExport loginName:{}",loginName);
//        long count = Arrays.stream(EXPORT_ORDER_USER).filter(exportUser -> exportUser.equals(loginName)).count();
//        if(count==0){
//            throw new BusinessException("对不起，您当前没有权限导出订单数据");
//        }
        req.setOptUserName(systemUser.getLoginName());
        req.setOptUserRealName(systemUser.getRealName());
        String ip = IpUtils.getIpAddr(request);
        req.setIpAddress(ip);
        String result = orderService.exportExpressOrder(req, null);
        log.info(":>>> 导出发货订单结果:{}", result);
        if (StringUtils.isNotBlank(result)) {
            return RestResultBuilder.builder().success(result).build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    /**
     * 合单订单导出
     *
     * @param
     * @param
     */
    @PostMapping("/order-single/export")
    @RequestActivityAuth(activityId = "#req.activityId")
    public RestResult singleOrderExpressExport(@RequestBody OrderRequest req, HttpServletRequest request) {
        req.setUserId(AuthUtils.getUserId());
        SystemUser systemUser = userService.get(req.getUserId());
        if (Objects.isNull(systemUser)) {
            throw new BusinessException("没有权限导出订单");
        }
        String loginName = systemUser.getLoginName();
        log.info("【导出订单】orderExpressExport loginName:{}",loginName);
//        long count = Arrays.stream(EXPORT_ORDER_USER).filter(exportUser -> exportUser.equals(loginName)).count();
//        if(count==0){
//            throw new BusinessException("对不起，您当前没有权限导出订单数据");
//        }
        req.setOptUserName(systemUser.getLoginName());
        req.setOptUserRealName(systemUser.getRealName());
        String ip = IpUtils.getIpAddr(request);
        req.setIpAddress(ip);
        String result = orderService.exportExpressOrder(req, null);
        log.info(":>>> 导出发货订单结果:{}", result);
        if (StringUtils.isNotBlank(result)) {
            return RestResultBuilder.builder().success(result).build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    @PostMapping("/order/pre-refund")
    public RestResult preRefund(@RequestBody OrderRefundOptVO req) {
        String comId = AuthUtils.getComId();
        req.setRefundApplyUserType("platform");
        req.setOptName(AuthUtils.getLoginName());
        boolean res = orderService.preRefund(req);
        if (res) {
            return RestResultBuilder.builder().success().build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    @PostMapping("/order/do-refund")
    public RestResult doRefund(@RequestBody OrderRefundOptVO req) {
        String comId = AuthUtils.getComId();
        req.setOptName(AuthUtils.getLoginName());
        req.setSourcePlatform("赞我云平台");
        boolean res = orderService.doRefund(req);
        if (res) {
            return RestResultBuilder.builder().success().build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    /**
     * 批量发货，对应前端按钮
     *
     * @param
     * @return
     */
    @PostMapping("/order/ship/import")
    public RestResult shipImport(@RequestParam("file") MultipartFile file,
                                 @RequestParam(value = "activityId", required = false) String activityId,
                                 @RequestParam("sendMsg") Boolean sendMsg,
                                 @RequestParam(value = "mode", required = false) String mode ){
        try {
            String fileName = file.getOriginalFilename();
            log.info(":>>> 批量发货文件:{}", fileName);
            if(StringUtils.isBlank(mode)){
                mode="V1";
            }
            Map<String, Object> res = orderService.orderImport(file.getBytes(), fileName, activityId, sendMsg,mode);
            return RestResultBuilder.builder().success(res).build();

        } catch (Exception e) {
            log.info(":>>> 导入发货记录错误:{}", e);
            return RestResultBuilder.builder().failure().build();
        }
    }

    /**
     * 批量退款
     *
     * @param
     * @return
     */
    @PostMapping("/order/batch/do-refund")
    public RestResult batchDoRefund(@RequestParam("file") MultipartFile file) {
        String userName = AuthUtils.getLoginName();
        if (!"weiyingying".equals(userName) && !"dongyan".equals(userName)) {
            log.error(":>>> 批量退款非张雪和朱怀琦账户");
            throw new BusinessException("非法操作,请自重");
        }
        try {
            String fileName = file.getOriginalFilename();
            log.info(":>>> 批量发货文件:{}", fileName);
            Map<String, Object> res = orderService.batchDoRefund(file.getBytes(), fileName, AuthUtils.getLoginName());
            return RestResultBuilder.builder().success(res).build();
        } catch (Exception e) {
            log.info(":>>> 导入发货记录错误:{}", e);
            return RestResultBuilder.builder().failure().build();
        }
    }

    @PostMapping("/order/tips/import")
    public RestResult importOrderTipss(@RequestParam("file") MultipartFile file,
                                       @RequestParam("activityId") String activityId) {
        try {
            String fileName = file.getOriginalFilename();
            log.info(":>>> 导入订单提示语文件:{}", fileName);
            Map<String, Object> res = orderInfoTipService.orderTpsImport(file.getBytes(), fileName, activityId);
            return RestResultBuilder.builder().success(res).build();
        } catch (Exception e) {
            log.info(":>>> 导入订单提示语文件错误:{}", e);
            return RestResultBuilder.builder().failure().build();
        }
    }

    @GetMapping("/order/refund/enable")
    public RestResult enableRefund(@RequestParam("orderNo") String orderNo) {
        return RestResultBuilder.builder().success(orderService.enableRefund(orderNo)).build();
    }

    @GetMapping("/order/university-s")
    public QResult sUniversity(@RequestParam(value = "total", required = true) Long total) {
        try {
            orderInfoTipService.statisticsActivity(total);
            return QResult.success("ok");
        } catch (Exception e) {
            log.error(":>>> 订单统计大学人数错误:{}", e);
            return QResult.fail("订单统计大学人数错误");
        }

    }

    @GetMapping("/order/update-status")
    public QResult updateStatus() {
        try {
            orderService.updateStatus();
            return QResult.success("ok");
        } catch (Exception e) {
            log.error(":>>> 订单状态补偿错误:{}", e);
            return QResult.fail("订单状态补偿错误");
        }

    }

    /**
     * 退款订单导出
     *
     * @param
     * @param
     */
    @PostMapping("/order-refund/export")
    @RequestActivityAuth(activityId = "#req.activityId")
    public RestResult orderRefundExport(@RequestBody OrderRequest req, HttpServletRequest request) {
        req.setUserId(AuthUtils.getUserId());
        SystemUser systemUser = userService.get(req.getUserId());
        if (Objects.isNull(systemUser)) {
            throw new BusinessException("没有权限导出订单");
        }
        String loginName = systemUser.getLoginName();
        log.info("【导出订单】orderExpressExport loginName:{}",loginName);
//        long count = Arrays.stream(EXPORT_ORDER_USER).filter(exportUser -> exportUser.equals(loginName)).count();
//        if(count==0){
//            throw new BusinessException("对不起，您当前没有权限导出订单数据");
//        }
        req.setOptUserName(systemUser.getLoginName());
        req.setOptUserRealName(systemUser.getRealName());
        String ip = IpUtils.getIpAddr(request);
        req.setIpAddress(ip);
        String result = orderService.exportRefundOrder(req, null);
        log.info(":>>> 导出发货订单结果:{}", result);
        if (StringUtils.isNotBlank(result)) {
            return RestResultBuilder.builder().success(result).build();
        }
        return RestResultBuilder.builder().failure().build();
    }
    /**
     * 补充订单
     *
     * @param
     * @return
     */
    @PostMapping("/order/re/do")
    public RestResult reDoOrder(@RequestParam("file") MultipartFile file,
                                 @RequestParam(value = "activityId") String activityId
                                 ,@RequestParam(value = "batchId") String batchId){
        try {
            String optUser=AuthUtils.getLoginName();
            if(!"zhouqiao".equals(optUser)&&!"zhuhuaiqi".equals(optUser)){
                return RestResultBuilder.builder().failure("无操作权限").build();
            }
            String fileName = file.getOriginalFilename();
            log.info(":>>> 补充订单文件:{},批次号:{}", fileName,batchId);
            Map<String, Object> res = orderService.reDoOrder(file.getBytes(), fileName, activityId,batchId);
            return RestResultBuilder.builder().success(res).build();
        } catch (Exception e) {
            log.info(":>>> 补充订单文件错误:{}", e);
            return RestResultBuilder.builder().failure().build();
        }
    }
}
